//
//  Pan.swift
//  Demo3
//
//  Created by Bigboss on 2025/3/7.
//

import SwiftUI

struct DeviceInfoPanel: View {
    @Binding var temperature: Double
    @Binding var humidity: Double
    
    var body: some View {
        VStack(spacing: 15) {
            Text("23号机房状态")
                .font(.system(size: 18, weight: .bold))
                .padding(.bottom, 5)
            
            StatusItem(
                icon: "thermometer",
                label: "TEMPERATURE",
                value: "\(Int(temperature))°C"
            )
            
            StatusItem(
                icon: "humidity",
                label: "HUMIDITY",
                value: "\(Int(humidity))%"
            )
            
            Button(action: refreshData) {
                Text("REFRESH DATA")
                    .font(.system(size: 14, weight: .semibold))
                    .frame(maxWidth: .infinity)
            }
            .buttonStyle(.borderedProminent)
            .padding(.top, 8)
        }
        .padding(20)
        
        .frame(width: 280)
        .glassBackgroundEffect()
        .cornerRadius(16)
    }
    
    private func refreshData() {
        temperature = Double.random(in: 20...30)
        humidity = Double.random(in: 50...70)
    }
}

struct StatusItem: View {
    let icon: String
    let label: String
    let value: String
    
    var body: some View {
        HStack {
            Image(systemName: icon)
                .frame(width: 30)
            
            VStack(alignment: .leading) {
                Text(label)
                    .font(.system(size: 12))
                    .foregroundColor(.secondary)
                
                Text(value)
                    .font(.system(size: 16, weight: .medium))
            }
            
            Spacer()
        }
        .padding(10)
        .background(Color.black.opacity(0.1))
        .cornerRadius(8)
    }
}


/// 警告面板
struct WarningPanelView: View {
    @EnvironmentObject var appModel: AppModel
    
    @StateObject private var audioManager = AudioManager.shared
    
    let warnings = [
        ("Equipment Overheat", "DANGER: A-01 Equipment Room Temperature Exceeds 60°C"),
        ("Voltage Anomaly", "WARNING: Phase B Voltage Fluctuation Exceeds 15% in Power Distribution Cabinet"),
        ("Communication Failure", "CAUTION: PLC Controller Connection Lost")
    ]
    
    
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            Text("WARNING")
                .font(.system(size: 24, weight: .bold))
                .foregroundColor(.red)
                .padding(.bottom, 8)
            
            ForEach(warnings.indices, id: \.self) { index in
                WarningButton(
                    title: warnings[index].0,
                    description: warnings[index].1
                ) {
                    /// 添加音效
                    audioManager.play(.sceneTransition, volume: 0.8)
                    withAnimation(.easeOut(duration: 0.3)) {
                        appModel.currentTestView = .distributionRoom
                        audioManager.play(.sceneTransition, volume: 1.0)
                        
                    }
                }
                .transition(.opacity.combined(with: .scale))
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 15)
                .fill(Color.black.opacity(0.9))
                .overlay(
                    RoundedRectangle(cornerRadius: 15)
                        .stroke(Color.red, lineWidth: 2)
                )
        )
        .frame(maxWidth: 800)
    }
}

struct WarningPanelView2: View {
    @EnvironmentObject var appModel: AppModel
    @StateObject private var audioManager = AudioManager.shared // 添加音频管理器
    
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack(alignment: .center, spacing: 16) {
                // 左侧图标
                Image("pdx")
                    .resizable()
                    .scaledToFit()
                    .frame(width: 40, height: 40)
                    .padding(.leading, 8)
                    .foregroundColor(.red)
                
                // 中间文字内容
                VStack(alignment: .leading, spacing: 4) {
                    Text("WARNING")
                        .font(.system(.subheadline, design: .rounded, weight: .semibold))
                        .foregroundColor(.white)
                    
                    Text("配电箱告警")
                        .font(.caption)
                        .foregroundColor(.white.opacity(0.5))
                }
                
                Spacer()
                
                // 右侧关闭按钮
                Button(action: {
                    withAnimation {
                        //                        appModel.currentTestView = .none
                    }
                }) {
                    Image(systemName: "xmark.circle.fill")
                        .foregroundColor(.white.opacity(0.8))
                        .font(.system(size: 20))
                }
                .frame(width: 10, height: 10)
                .padding(.trailing, 8)
            }
            .padding(.vertical, 12)
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 18)
                .fill(Color.gray.opacity(0.2))
        )
        .frame(width: 280, height: 100, alignment: .center)
        // 添加整体点击事件
        .contentShape(RoundedRectangle(cornerRadius: 18)) // 定义点击区域
        .onTapGesture {
            audioManager.play(.sceneTransition, volume: 0.8)
            withAnimation(.easeOut(duration: 0.3)) {
                appModel.currentTestView = .distributionRoom
                audioManager.play(.sceneTransition, volume: 1.0)
            }
        }
        .glassBackgroundEffect()
        
    }
}


struct WarningPanelView3: View {
    @EnvironmentObject var appModel: AppModel
    @StateObject private var audioManager = AudioManager.shared
    
    var body: some View {
        HStack(alignment: .center, spacing: 12) {
            // 使用 Spacer 包裹内容实现整体居中
            Spacer(minLength: 0)
            
            // 警告图标
            Image(systemName: "exclamationmark.triangle.fill")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 28, height: 28)
                .foregroundColor(.red)
            
            // 文字内容
            Text("故障")
                .font(.system(size: 17, weight: .medium, design: .rounded))
                .foregroundColor(.white)
            
            Spacer(minLength: 0)
        }
        .frame(width: 140, height: 50)
        .background(
            RoundedRectangle(cornerRadius: 12)
                .fill(Color.gray.opacity(0.2))
        )
        .contentShape(RoundedRectangle(cornerRadius: 12))
        .glassBackgroundEffect()
    }
}

// 独立封装的警告按钮组件
struct WarningButton: View {
    let title: String
    let description: String
    let action: () -> Void
    
    var body: some View {
        Button(action: action) {
            HStack(spacing: 12) {
                Image(systemName: "exclamationmark.triangle.fill")
                    .foregroundColor(.yellow)
                    .font(.title3)
                
                VStack(alignment: .leading, spacing: 4) {
                    Text(title)
                        .font(.system(.subheadline, design: .rounded, weight: .semibold))
                        .foregroundColor(.white)
                    
                    Text(description)
                        .font(.caption)
                        .foregroundColor(.white.opacity(0.8))
                        .lineLimit(2)
                }
                
            }
            .padding(12)
            .background(
                RoundedRectangle(cornerRadius: 10)
                    .fill(Color.red.opacity(0.2))
                    .shadow(color: .red.opacity(0.4), radius: 6, x: 0, y: 3)
            )
        }
        .buttonStyle(WarningButtonStyle()) // 使用自定义按钮样式[3](@ref)
    }
}

// 自定义按钮动画样式
struct WarningButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .scaleEffect(configuration.isPressed ? 0.97 : 1.0)
            .brightness(configuration.isPressed ? 0.1 : 0)
            .animation(.interactiveSpring(response: 0.3, dampingFraction: 0.6), value: configuration.isPressed)
    }
}


struct FaultAlertPanel: View {
    let deviceName: String
    let faultType: FaultType
    let timestamp: String
    
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            // 警示标题栏
            HStack(spacing: 12) {
                Image(systemName: "exclamationmark.octagon.fill")
                    .foregroundColor(.red)
                    .font(.largeTitle)
                
                VStack(alignment: .leading) {
                    Text("Equipment Abnormality Alarm")
                        .font(.system(.title3, design: .rounded, weight: .bold))
                        .foregroundColor(.red)
                    
                    Text("ALERT: \(faultType.localizedDescription)")
                        .font(.system(.caption, design: .monospaced))
                        .foregroundColor(.red.opacity(0.8))
                }
            }
            .padding(.bottom, 8)
            
            // 核心参数区
            VStack(spacing: 8) {
                ParameterRow(
                    icon: "thermometer.sun",
                    title: "Temperature",
                    value: "89°C",
                    unit: "TH: 75°C",
                    isCritical: true
                )
                
                ParameterRow(
                    icon: "clock.fill",
                    title: "Duration",
                    value: "2h 38m",
                    unit: "First alarm: \(timestamp)"
                )
            }
            .padding(.vertical, 8)
            
            //            // 设备信息区
            //            DetailInfoGrid(deviceName: deviceName)
            //
            //            // 操作按钮组
            //            HStack(spacing: 20) {
            //                ActionButton(icon: "power.circle", label: "远程断电", color: .red)
            //                ActionButton(icon: "phone.connection", label: "联系维保", color: .blue)
            //            }
            //            .padding(.top, 12)
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 12)
                .fill(Color.black.opacity(0.9))
                .overlay(
                    RoundedRectangle(cornerRadius: 12)
                        .stroke(LinearGradient(
                            gradient: Gradient(colors: [.red, .orange]),
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing),
                                lineWidth: 2)
                )
                .shadow(color: .red.opacity(0.4), radius: 10, x: 0, y: 5)
        )
        .frame(width: 400)
    }
}

// 故障类型枚举
enum FaultType: String {
    case overheat          = "E01"
    case voltageAnomaly   = "E02"
    case commFailure       = "E03"
    
    var localizedDescription: String {
        switch self {
        case .overheat:
            return "Over Temperature"
        case .voltageAnomaly:
            return "Voltage Anomaly"
        case .commFailure:
            return "Communication Failure"
        }
    }
}

// 参数行组件
private struct ParameterRow: View {
    let icon: String
    let title: String
    let value: String
    let unit: String
    var isCritical: Bool = false
    
    var body: some View {
        HStack {
            Image(systemName: icon)
                .foregroundColor(isCritical ? .orange : .gray)
            
            Text(title)
                .font(.system(.subheadline, design: .rounded))
                .frame(width: 88, alignment: .leading)
            
            Text(value)
                .font(.system(.body, design: .monospaced, weight: .bold))
                .foregroundColor(isCritical ? .orange : .white)
            
            Text(unit)
                .font(.system(.caption, design: .monospaced))
                .foregroundColor(.gray)
            
            Spacer()
        }
    }
}


struct EquipmentStatusView: View {
    // 添加关闭事件回调
    var onDismiss: () -> Void
    
    var body: some View {
        VStack(alignment: .leading, spacing: 20) {
            // 标题部分
            VStack(alignment: .leading, spacing: 12) {
                Text("421B-B（1）APKT配电箱")
                    .font(.title2).bold()
                ActionButton(text: "故障", color: .red)
            }
            
            // 数据分栏布局
            // 左侧数据列
            VStack(alignment: .leading, spacing: 12) {
                DataRow(title: "序列号：", value: "BPD2862372")
                DataRow(title: "运行时间：", value: "889天45分34秒")
                DataRow(title: "故障时间：", value: "45分34秒")
                DataRow(title: "故障次数：", value: "10")
                DataRow(title: "故障率：", value: "10%")
            }
            
            // 右侧操作按钮列
            HStack(spacing: 5) {
                ActionButton(text: "检测", color: .gray)
                ActionButton(text: "设备", color: .gray)
                ActionButton(text: "维保", color: .gray)
                ActionButton(text: "维修", color: .gray)
            }
            
            // 关闭按钮
            Button("Dismiss") {
                // 关闭操作
                onDismiss() // 触发回调
            }
            .frame(width: 300)
        }
        .padding()
        .frame(width: 400)
        .glassBackgroundEffect()
    }
}

// 自定义数据行组件
struct DataRow: View {
    let title: String
    let value: String
    
    var body: some View {
        HStack {
            Text(title).foregroundColor(.secondary)
            Text(value).bold()
        }
        .font(.system(size: 14))
    }
}

// 自定义操作按钮组件
struct ActionButton: View {
    let text: String
    let color: Color
    
    var body: some View {
        Button(text) {
            // 按钮操作
        }
        .buttonStyle(.borderedProminent)
        .tint(color)
        .controlSize(.small)
    }
}

// 电流显示组件
struct CurrentDisplay: View {
    let phase: String
    let value: String
    
    var body: some View {
        VStack {
            Text("\(phase)电流")
                .font(.caption)
                .foregroundColor(.secondary)
            Text(value)
                .font(.system(.body, design: .monospaced))
                .bold()
        }
        .padding()
        .background(Color.gray.opacity(0.2))
        .cornerRadius(8)
    }
}

// 分区标题组件
struct SectionTitle: View {
    let text: String
    
    init(_ text: String) {
        self.text = text
    }
    
    var body: some View {
        Text(text)
            .font(.headline)
            .padding(.vertical, 8)
            .frame(maxWidth: .infinity, alignment: .leading)
    }
}
